import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import * as _ from "lodash";
import { ReviewBackComponent } from '../review-back/review-back.component';
import { ViewDetailService } from './view-detail.service';
import { RevokeComponent } from '../revoke/revoke.component';
import { DataService } from 'app/services/data.service';
import { Util } from '../../../../../common/util';
import { SelectItem } from 'primeng/components/common/api';
import { ApplyFundGroupComponent } from '../../modal/apply-fund-group/apply-fund-group.component';
@Component({
  selector: 'app-view-detail',
  templateUrl: './view-detail.component.html',
  styleUrls: ['./view-detail.component.scss'],
  providers: [ViewDetailService]
})
export class ViewDetailComponent implements OnInit {
  // 撤销modal
  @ViewChild("viewDetailRevokeModal", { read: ViewContainerRef })
  viewDetailRevokeModal: ViewContainerRef;
  revokeComponent: ComponentRef<RevokeComponent>;
  // 适用基金组modal
  @ViewChild("viewApplyFundGroup", { read: ViewContainerRef })
  viewApplyFundGroup: ViewContainerRef;
  applyFundGroupComponent: ComponentRef<ApplyFundGroupComponent>;
  //下拉option数据
  public dictionaryInfo: SelectItem[];
  //列表克隆数据
  public cloneList: any;

  public elementShow: any = [];
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  //传入的菜单按钮权限数组
  public menuResource: any;
  // receivedItem接收的对象
  public receivedItem: any;

  public isCheckedAll: any;

  // 条目信息数据
  public listData: any = [];

  // 条目信息最后一条，用于查基本信息
  public lastInfoData: any;

  // 流程信息数据
  public flowInfoData: any;

  //查看明细类型,1代表条目录入批次模式查看明细，2代表条目复核批次模式查看明细
  public viewDetailType: any;

  //字典值列表
  public dictionaryList: any = {
    RISK_RECORD_TYPE: [],//属性
    NX_SOURCE: [],//条款出处
    RISK_ACCOUNT_TYPE: [],//适用基金组类别
    RISK_CTRL_METHOD: [],//事中控制方法
    RISK_CONTROL_AFTER: [],//事后监控方法
    MONITOR_REMARK: [],//风险等级
    RISK_CW_CTRL: [],//是否场外系统可控
    RISK_HS_CONTROL: []//是否事中系统可控
  }
  // 条目复核通过modal
  @ViewChild("review", { read: ViewContainerRef })
  review: ViewContainerRef;
  reviewComponent: ComponentRef<ReviewBackComponent>;

  // 返回modal
  @ViewChild("back", { read: ViewContainerRef })
  back: ViewContainerRef;
  backComponent: ComponentRef<ReviewBackComponent>;


  constructor(public resolver: ComponentFactoryResolver,
    public viewDetailService: ViewDetailService,
    public dataService: DataService) { }

  ngOnInit() {
    let that = this;
    // 多选下拉框
    // console.info(this.menuResource)
    window['$'](".select2").select2();
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    this.loadEntryInfoList();
    // 权限处理
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    // this.menuResourceSet = [];
    this.menuResourceSet = _.cloneDeep(this.menuResource)
    sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
    console.info(this.menuResourceSet)
    //加载下拉多选框
    this.dictionaryInfo = Util.loadPrimeSelect(this.dictionaryList.RISK_ACCOUNT_TYPE);
    this.dataService.nQDIIInputModelEmitter = new EventEmitter();
    this.dataService.nQDIIInputModelEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'index':
            that.listData[that.dataService.nQDIIIndexId].sFundGroupdsZh = that.dataService.nQDIIFGroupInfo;
            that.listData[that.dataService.nQDIIIndexId].sFundGroupds = that.dataService.nQDIIIdList;
            window['$']('#viewApplyFundGroup').modal('hide');
            break;
        }
      }
    })
    if (this.viewDetailType == '2') {
      this.controlDom('check-cancel');
    } else {
      this.controlDom('check');
    }

    // this.controlDom(this.listData,'check-cancel');
  }
  //适用基金组modal
  showApplyFundGroup(index?) {
    // 判断组件是否已创建，如果创建先注销
    if (this.applyFundGroupComponent && this.applyFundGroupComponent.instance) {
      this.applyFundGroupComponent.destroy();
    }
    // 动态创建组件的实例
    const applyFundGroupComponent = this.resolver.resolveComponentFactory(ApplyFundGroupComponent);
    this.applyFundGroupComponent = this.viewApplyFundGroup.createComponent(applyFundGroupComponent);
    if (index != null) {
      this.applyFundGroupComponent.instance.index = index;
      if (this.listData[index].sFundGroupds != '' && this.listData[index].sFundGroupds != null && this.listData[index].sFundGroupds != undefined) {
        this.applyFundGroupComponent.instance.checkedIdList = this.listData[index].sFundGroupds.split(',');
        console.log(this.listData[index].sFundGroupds.split(','))
      }

    }
    window['$']('#viewApplyFundGroup').modal('show');
  }
  // 显示modal
  showModal(index) {
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        checkProduct.push(item);
      }
    });
    if (checkProduct.length == 0) {
      window['swal']("提示", "请勾选数据后再操作！", "warning")
    } else {
      switch (index) {
        case '2':
          if (this.reviewComponent && this.reviewComponent.instance) {
            this.reviewComponent.destroy();
          }

          // 动态创建组件的实例
          const reviewBackComponent = this.resolver.resolveComponentFactory(ReviewBackComponent);
          this.reviewComponent = this.review.createComponent(reviewBackComponent);
          this.reviewComponent.instance.showTip = 3;
          this.reviewComponent.instance.postbody.pmsNqdiiJournalExtList = checkProduct;
          this.reviewComponent.instance.receivedItem = this.receivedItem;
          window['$']('#modal5').modal('show');

          break;
        case '3':
          if (this.backComponent && this.backComponent.instance) {
            this.backComponent.destroy();
          }

          // 动态创建组件的实例
          const backComponent = this.resolver.resolveComponentFactory(ReviewBackComponent);
          this.backComponent = this.back.createComponent(backComponent);
          this.backComponent.instance.showTip = 4;
          this.backComponent.instance.postbody.pmsNqdiiJournalExtList = checkProduct;
          this.backComponent.instance.receivedItem = this.receivedItem;
          window['$']('#modal6').modal('show');
          break;
      }
    }
  }

  // 列表全选
  checkedAll() {
    let that = this;
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, (item, index) => {
        item.isChecked = true;
        if (this.listData[index + 1] != undefined) {
          if (this.listData[index].nNjId == this.listData[index + 1].nNjId || this.listData[index].sOprState != '1') {
            this.listData[index].isChecked = false;
          }
        } else if (that.listData[index].sOprState != '1') {
          //判断处理状态是否为待处理，不是则全选后置为false
          this.listData[index].isChecked = false;
        }
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    let repeatCount = 0;
    _.forEach(this.listData, (item, index) => {
      if (this.listData[index + 1] != undefined) {

        if (this.listData[index].nNjId == this.listData[index + 1].nNjId || this.listData[index].sOprState != '1') {
          repeatCount++;
        }
      } else if (that.listData[index].sOprState != '1') {
        repeatCount++;
      }
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length + repeatCount == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 关闭modal
  hideModal() {
    window['$']('#modal4').modal('hide');

  }
  // 条目信息列表
  loadEntryInfoList() {
    console.log(this.receivedItem)
    let getbody = {
      nBatchNo: this.receivedItem.nBatchNo,
      pageIndex: 0,
      pageSize: 0
    }
    this.viewDetailService.entryInfoList(getbody).subscribe((data) => {
      if (data) {
        this.listData = data.list;
        _.forEach(this.listData, it => {
          if (it.sFundType != null) {
            it.sFundType = it.sFundType.split(",");
          }
        })
        if(data.list.length>0){
          this.elementList(data.list.length);
        }
        console.log(this.listData);
        this.cloneList = _.cloneDeep(this.listData);
        this.lastInfoData = _.last(this.listData);
        this.loadFlowInfo(this.lastInfoData.nBatchNo, this.lastInfoData.nNjId);
      }
    })
  }
  // 流程信息列表
  loadFlowInfo(nBatchNo, nNjId) {
    let getbody = {
      nBatchNo: nBatchNo,
      nNjId: nNjId,
      pageIndex: 0,
      pageSize: 0
    }
    console.log(getbody);
    this.viewDetailService.flowInfoList(getbody).subscribe((data) => {
      if (data) {
        this.flowInfoData = data.list;
      }
    })
  }
  //保存
  save() {
    let that = this;
    let putBody: any = [];
    let listData = _.cloneDeep(this.listData);
    _.forEach(listData, item => {
      let isNull: any = true;
      if (item.isChecked) {
        // delete item.sOprDateStart;
        // delete item.sOprDateEnd;
        // delete item.nBatchNoStart;
        // delete item.nBatchNoEnd;
        // delete item.nBatchNumber;
        // delete item.sLaunchDate;
        // delete item.sCheck;
        // delete item.sCreator;
        // delete item.sCheckPerson;
        delete item.isChecked;
        //判断选中的对象的sFundType是否为数组
        if (Array.isArray(item.sFundType)) {
          item.sFundType = item.sFundType.join(',');
        }
        putBody.push(item)
      }
    })
    console.log(JSON.stringify(putBody))
    if (putBody.length == 0) {
      window['swal']("提示", "请选择一条或者多条不为空的数据", "warning")
    } else {
      window['swal']({
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        title: "提示",
        text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否保存选中的信息" + "</div>",
        html: true
      },
        function (isConfirm) {
          if (isConfirm) {
            that.viewDetailService.save(putBody).subscribe(data => {
              if (data) {
                window['swal']("提示", "保存成功", "success")
                that.dataService.nQDIIBatchModelEmitter.emit('refreshBatchList');
              }
            })
          }
        })
    }
  }
  //撤销
  recall() {
    let that = this;
    let checkedItem = [];
    let listData = _.cloneDeep(that.listData);
    let lockList: any = [];
    //用于判断是否选择了复核的数据
    let sFlowStepList: any = [];
    _.forEach(listData, item => {
      if (item.isChecked == true) {
        delete item.isChecked;
        //判断选中的对象的sFundType是否为数组
        if (Array.isArray(item.sFundType)) {
          item.sFundType = item.sFundType.join(',');
        }
        if (item.sFlowStep == '1') {
          sFlowStepList.push(item.nNjId)
        }
        checkedItem.push(item);
        lockList.push(item.nId);
      }
    });
    let putBody = checkedItem

    console.log(JSON.stringify(putBody))
    if (checkedItem.length != 0) {
      let getBody = {
        "nIdList": lockList
      }
      console.log(getBody)
      if (sFlowStepList.length > 0) {
        window['swal']("提示", "请选择流程状态为复核的数据进行撤销", "warning")
      } else {
        that.viewDetailService.lock(getBody).subscribe(data => {
          if (data == true) {
            that.showRevoke(putBody)
          } else {
            window['swal']("提示", "上锁失败", "warning");
          }
        })
      }

    }
    else {
      window['swal']("提示", "请选择一条或者多条数据进行撤销", "warning")
    }
  }
  //展示撤销modal
  showRevoke(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.revokeComponent && this.revokeComponent.instance) {
      this.revokeComponent.destroy();
    }
    if (item.length != 0) {
      // 动态创建组件的实例
      const revokeComponent = this.resolver.resolveComponentFactory(RevokeComponent);
      this.revokeComponent = this.viewDetailRevokeModal.createComponent(revokeComponent);
      this.revokeComponent.instance.RoutepostBody = item
      window['$']('#viewDetailRevokeModal').modal('show');
    } else {
      window['swal']("提示", "请选择一条数据", "warning")
    }

  }
  //根据字典key查询value
  getValueByKey(key, dictionaryName) {
    let that = this;
    let info: any;
    switch (dictionaryName) {
      case 'RISK_RECORD_TYPE':
        info = _.filter(that.dictionaryList.RISK_RECORD_TYPE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'NX_SOURCE':
        info = _.filter(that.dictionaryList.NX_SOURCE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_ACCOUNT_TYPE':
        info = _.filter(that.dictionaryList.RISK_ACCOUNT_TYPE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_CTRL_METHOD':
        info = _.filter(that.dictionaryList.RISK_CTRL_METHOD, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_CONTROL_AFTER':
        info = _.filter(that.dictionaryList.RISK_CONTROL_AFTER, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'MONITOR_REMARK':
        info = _.filter(that.dictionaryList.MONITOR_REMARK, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_CW_CTRL':
        info = _.filter(that.dictionaryList.RISK_CW_CTRL, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_HS_CONTROL':
        info = _.filter(that.dictionaryList.RISK_HS_CONTROL, (item: any) => {
          return item.sItemKey == key
        })
        break;
    }
    // console.log("纳尼？？")
    // console.log(info[0])
    return info[0].sItemValue;
  }
  //根据参数判断需要转义的字段
  translateByName(i: any, name: any, itemCode: any) {
    let that = this;
    let nameZh = name + 'Zh';
    if (that.listData[i][name] != '' && that.listData[i][name] != null && that.listData[i][name] != undefined) {
      this.listData[i][nameZh] = this.getValueByKey(that.listData[i][name], itemCode)
    } else {
      this.listData[i][nameZh] = '';
    }
  }
  // 修改标蓝(i为下标,value为修改后的值,name为字段名)
  inputChange(i: any, value: any, name: any, itemCode?) {

    let that = this;
    //转义
    if (itemCode != undefined) {
      this.translateByName(i, name, itemCode);
    }
    // 定位tr
    let index = i + 1;
    // 定位输入框和选择框
    let id = "#route-table tbody tr:nth-child(" + index + ") td div[id=" + name + "]";
    // let id2 = "#input-table tbody tr:nth-child(" + index + ") td select[name=" + name + "]";
    // 获取当前修改对象
    let item = this.cloneList[i];
    // 循环对象
    for (let key in item) {
      // 判断字段名是否相等
      if (key == name) {
        // 判断原值是否为null(后端空值返回null,前端空值为'',实际都为空,相等)
        if (item[key] == null) {
          if (value == '') {
            window['$'](id).removeClass('triangle-topleft');
          } else {
            window['$'](id).addClass('triangle-topleft');
          }
        } else {
          // 判断原值不为null,直接对比
          if (item[key] == value) {
            console.log("触发1")
            window['$'](id).removeClass('triangle-topleft');
          } else {
            console.log("触发2")
            window['$'](id).addClass('triangle-topleft');
          }
        }
      }
    }
  }
  //根据编号是否相同操控dom
  controlDom(checkId) {
    let that = this;
    setTimeout(() => {
      if (this.listData != null && that.listData.length != 0) {
        for (let i = 0; i < that.listData.length; i++) {
          // Util.loadSelect(this.dictionaryList.QD_ACCOUNT_TYPE, 'QDIIRouteFundType' + i)
          // window['$']('#QDIIRouteFundType' + i).selectpicker('val', this.listData[i].sFundType);
          if (that.listData[i + 1] != undefined) {
            if (that.listData[i].nNjId == that.listData[i + 1].nNjId) {
              // console.log(checkId + i)
              window['$']('#' + checkId + i).remove();
              _.forIn(that.listData[i], (item1, key1) => {
                let index1 = i + 1;
                let index2 = i + 2;
                let id1 = "#route-table tbody tr:nth-child(" + index1 + ") td input[name=" + key1 + "]";
                let id2 = "#route-table tbody tr:nth-child(" + index2 + ") td input[name=" + key1 + "]";
                let id3 = "#route-table tbody tr:nth-child(" + index1 + ") td select[name=" + key1 + "]";
                let id4 = "#route-table tbody tr:nth-child(" + index2 + ") td select[name=" + key1 + "]";
                let id5 = "#route-table tbody tr:nth-child(" + index1 + ") td div[id=" + key1 + "]";
                let id6 = "#route-table tbody tr:nth-child(" + index2 + ") td div[id=" + key1 + "]";
                if (item1 == that.listData[i + 1][key1]) {
                  window['$'](id1).removeClass('font-color');
                  window['$'](id2).removeClass('font-color');
                  window['$'](id3).removeClass('font-color');
                  window['$'](id4).removeClass('font-color');
                  window['$'](id5).removeClass('font-color');
                  window['$'](id6).removeClass('font-color');
                } else {
                  console.log("触发2")
                  window['$'](id1).removeClass('font-color');
                  window['$'](id3).removeClass('font-color');
                  window['$'](id5).removeClass('font-color');
                }
              })
            } else {
              //判断处理状态是否为待处理，不是则去除多选按钮
              if (that.listData[i].sOprState != '1') {
                window['$']('#' + checkId + i).remove();
              }
            }
          } else {
            //判断处理状态是否为待处理，不是则去除多选按钮
            if (that.listData[i].sOprState != '1') {
              window['$']('#' + checkId + i).remove();
            }
          }
        }
      } else {
        this.controlDom(checkId);
      }
    });
  }
  //添加空白数据进入elementList
  elementList(index) {
    this.elementShow = [];
    for (let i = 0; i < index; i++) {
      this.elementShow.push({
        nNdId: "",
        nSortNo: "",
        sState: "",
        nBatchNo: "",
        sValid: "",
        sItemType: "",
        sFileName: "",
        sFileSource: "",
        sFundGroupds: "",
        sFundGroupdsZh: "",
        sFundType: "",
        sState2: "",
        sBatchNo2: "",
        f1: "",
        f2: "",
        f3: "",
        f4: "",
        f5: "",
        f6: "",
        f7: "",
        f8: "",
        f9: "",
        f10: "",
        f11: "",
        f12: "",
        f13: "",
        f14: "",
        f15: "",
        f16: "",
        f17: "",
        f18: "",
        f19: "",
        f20: ""
      })
    }
  }
  //点击修改单元格字段状态
  changeEleStatus(index, field, type) {
    if (type == '1') {
      this.elementShow[index][field] = '1';
    } else {
      this.elementShow[index][field] = '';
    }

  }
}
